package com.supostacks.xuetangerp.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSONObject;
import com.supostacks.rpc.server.dto.BaseDto;
import com.supostacks.rpc.server.dto.ResourceInfoDto;
import com.supostacks.rpc.server.dto.UserDto;
import com.supostacks.rpc.server.req.DeployReq;
import com.supostacks.rpc.server.req.FetchReq;
import com.supostacks.rpc.server.res.XResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

@RequestMapping("/resource")
@RestController
public class ResourceInfoController extends BaseController {
    @Override
    public BaseDto buildData(JSONObject json) {
        return JSONObject.toJavaObject(json, ResourceInfoDto.class);
    }

    @Override
    public BaseDto takeBaseDto() {
        return new ResourceInfoDto();
    }


    @PostMapping("/insert1")
    public SaResult insert(
            @RequestParam("file") MultipartFile file,
            @RequestParam("data") String data) {

        try {
            JSONObject d = JSONObject.parseObject(data);
            ResourceInfoDto resourceInfoDto = JSONObject.toJavaObject(
                    d,
                    ResourceInfoDto.class
            );
            resourceInfoDto.setCoverImage(file.getBytes());

            DeployReq req = DeployReq.builder().type("insert")
                    .data(resourceInfoDto).build();

            XResult res = dataDeployService.deploy(req);
            return SaResult.code(res.getCode()).setMsg(res.getMsg()).setData(res.getResult());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/update/info")
    public SaResult update(
            @RequestParam("file") MultipartFile file,
            @RequestParam("data") String data) {

        try {
            JSONObject d = JSONObject.parseObject(data);
            ResourceInfoDto resourceInfoDto = JSONObject.toJavaObject(
                    d,
                    ResourceInfoDto.class
            );

            resourceInfoDto.setCoverImage(file.getBytes());
            DeployReq req = DeployReq.builder().type("update")
                    .data(resourceInfoDto).build();

            XResult res = dataDeployService.deploy(req);
            return SaResult.code(res.getCode()).setMsg(res.getMsg()).setData(res.getResult());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public SaResult selectById(String id) {
        SaResult saResult = super.selectById(id);
        Object data = saResult.getData();
        if (data != null) {
            Map<String, Object> result = (Map<String, Object>) data;
            Object type = result.get("type");
            if (!"免费项目".equals(type)) {
                result.put("url", "");
            }
            saResult.setData(result);
        }
        return saResult;
    }

    @SaCheckLogin
    @RequestMapping("/select/url")
    public SaResult selectUrl(@RequestParam("id") String id) {
        String userId = StpUtil.getLoginIdAsString();
        FetchReq userReq = FetchReq.builder().type("selectById")
                .option(JSONObject.parseObject("{\"id\":\"" + userId + "\"}"))
                .data(new UserDto()).build();

        XResult userXResult = dataFetchService.fetch(userReq);
        Object data = userXResult.getResult();
        if (data instanceof UserDto) {
            UserDto userDto = (UserDto) data;
            Date now = new Date();
            Date expireTime = userDto.getExpireTime();
            if (now.after(expireTime)) {//已过期
                return SaResult.error("您的会员已过期，请联系客服");
            }
        }

        SaResult saResult = super.selectById(id);
        Object _data = saResult.getData();
        if (_data != null) {
            Map<String, Object> result = (Map<String, Object>) _data;
            Object url = result.get("url");
            saResult.setData(url);
        }
        return saResult;
    }

    @RequestMapping("/search")
    public SaResult search(@RequestBody JSONObject option) {
        FetchReq req = FetchReq.builder().option(option)
                .type("search").data(takeBaseDto())
                .build();
        XResult xResult = dataFetchService.fetch(req);
        return SaResult.code(xResult.getCode()).setMsg(xResult.getMsg()).setData(xResult.getResult());
    }
}
